package io.gitee.lglbc.easy.security.core.capatcha;

import cn.hutool.core.codec.Base64;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.gitee.lglbc.easy.security.open.EasyLogin;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author 乐哥聊编程
 */
@RestController
@RequestMapping("/security")
@Slf4j
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private EasyLogin easyLogin;

    public static String getBase64(BufferedImage image) {
        String base64 = null;
        try {
            //输出流
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            base64 = "data:image/jpeg;base64," + Base64.encode(stream.toByteArray());
            log.info("生成的图片验证码base64:{}", base64);
            stream.close();
        } catch (IOException e) {
            log.error("生成生成的图片验证码base64失败：{}", e.getMessage());
            e.printStackTrace();
        }
        return base64;

    }

    @GetMapping(value = "/captcha")
    public Object captcha(HttpServletRequest request, HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String text = defaultKaptcha.createText();
        BufferedImage image = defaultKaptcha.createImage(text);
        return easyLogin.saveCaptcha(text, getBase64(image));
    }
}
